<template>
  <div class="sale-return-create-page">
    <el-page-header content="新增销售退货" @back="handleBack" class="page-header" />

    <el-card shadow="never" class="form-card">
      <template #header>
        <div class="card-header">
          <span class="title">基础信息</span>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px" class="info-form">
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item prop="saleReturnsNo">
              <template #label>
                <span>退货单号</span>
              </template>
              <el-input v-model="form.saleReturnsNo" placeholder="自动获取系统编号" readonly class="readonly-input">
                <template #append>
                  <el-button @click="handleGenerateNo" :loading="generatingCode">自动生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="退货日期" prop="saleReturnsDate">
              <el-date-picker
                v-model="form.saleReturnsDate"
                type="date"
                placeholder="请选择退货日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售单号" prop="salesOrderNo">
              <el-input
                v-model="form.salesOrderNo"
                placeholder="请选择销售单"
                readonly
                @click="openSalesOrderDialog"
              >
                <template #suffix>
                  <el-button icon="Search" link @click.stop="openSalesOrderDialog" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="form.customerName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系人">
              <el-input v-model="form.contactName" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式">
              <el-input v-model="form.contactPhone" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售部门">
              <el-input v-model="form.salesDepartment" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="6">
            <el-form-item label="销售负责人">
              <el-input v-model="form.salesOwner" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退货原因">
              <el-input v-model="form.saleReturnReason" placeholder="请输入退货原因" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card shadow="never" class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="title">退货明细</span>
          <div class="actions">
            <el-button type="primary" @click="openGoodsDialog" :disabled="!form.salesOrderId">添加</el-button>
            <el-button type="danger" plain @click="handleRemoveSelected" :disabled="selectedDetailRows.length === 0">
              移除
            </el-button>
          </div>
        </div>
      </template>
      <el-table
        :data="detailRows"
        border
        stripe
        style="width: 100%"
        ref="detailTableRef"
        @selection-change="handleDetailSelectionChange"
        :empty-text="form.salesOrderId ? '请添加退货货品' : '请先选择销售单'"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="specificationModel" label="规格型号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column label="可退数量" width="100" align="right">
          <template #default="{ row }">
            {{ Number(row.returnableQuantity ?? row.salesQuantity ?? 0) }}
          </template>
        </el-table-column>
        <el-table-column label="退货数量" width="140">
          <template #default="{ row }">
            <el-input-number
              v-model="row.returnQuantity"
              :min="0"
              :max="row.returnableQuantity || 999999"
              :precision="2"
              :step="1"
              controls-position="right"
              @change="recalcRow(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="退货单价" width="140" align="right">
          <template #default="{ row }">
            <el-input-number
              v-model="row.unitPrice"
              :min="0"
              :precision="4"
              :step="1"
              controls-position="right"
              @change="recalcRow(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="金额" width="140" align="right">
          <template #default="{ row }">
            ¥{{ Number(row.amount ?? 0).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="160">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="请输入备注" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row }">
            <el-button link type="danger" @click="removeDetailRow(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="detail-summary" v-if="detailRows.length">
        <span>退货种类：<strong>{{ detailRows.length }}</strong></span>
        <span>退货数量：<strong>{{ summary.totalQuantity }}</strong></span>
        <span>退货金额：<strong>¥{{ summary.totalAmount.toFixed(2) }}</strong></span>
      </div>
    </el-card>

    <div class="fixed-footer">
      <div class="footer-actions">
        <el-button @click="handleBack">关闭</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
        <el-button type="success" @click="handleSaveAndNew" :loading="saving">保存并新增</el-button>
      </div>
    </div>

    <!-- 销售单选择弹窗 -->
    <el-dialog v-model="salesOrderDialog.visible" title="选择销售单" width="900px">
      <el-form :model="salesOrderDialog.search" inline class="dialog-form">
        <el-form-item label="销售单号">
          <el-input v-model="salesOrderDialog.search.salesOrderNo" placeholder="请输入销售单号" />
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select v-model="salesOrderDialog.search.salesOrderStatus" placeholder="请选择" clearable style="width: 150px">           
            <el-option label="未出库" :value="3" />
            <el-option label="部分出库" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="salesOrderDialog.search.customerName" placeholder="请输入客户" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadSalesOrders">查询</el-button>
          <el-button @click="resetSalesOrderDialog">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        :data="salesOrderDialog.list"
        height="400px"
        border
        stripe
        v-loading="salesOrderDialog.loading"
        @row-dblclick="handlePickSalesOrder"
      >
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="salesOrderNo" label="销售单号" width="150" />
        <el-table-column label="单据状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getSalesOrderStatusTag(row.salesOrderStatus)" size="small">
              {{ getSalesOrderStatusText(row.salesOrderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesOrderDate" label="销售日期" width="140">
          <template #default="{ row }">
            {{ formatDate(row.salesOrderDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" min-width="160" show-overflow-tooltip />
        <el-table-column label="销售部门" min-width="140" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.organizationName || row.salesDepartment || row.salesOrderDepartment || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="销售负责人" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.userName || row.salesOwner || row.salesOrderUser || row.salesUser || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">
              ¥{{ Number(row.salesOrderAmount ?? row.saleAmount ?? row.amount ?? 0).toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button link type="primary" @click="handlePickSalesOrder(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 货品选择弹窗 -->
    <el-dialog v-model="goodsDialog.visible" title="添加货品" width="900px">
      <div class="dialog-tip" v-if="!form.salesOrderId">
        请先选择销售单
      </div>
      <el-table
        v-else
        :data="goodsDialog.list"
        border
        height="440px"
        stripe
        v-loading="goodsDialog.loading"
        @selection-change="goodsDialogSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip />
        <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="specificationModel" label="规格型号" min-width="140" show-overflow-tooltip />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="salesQuantity" label="销售数量" width="100" align="right" />
        <el-table-column prop="returnableQuantity" label="可退数量" width="100" align="right" />
        <el-table-column prop="unitPrice" label="销售单价" width="120" align="right">
          <template #default="{ row }">
            ¥{{ Number(row.unitPrice ?? 0).toFixed(4) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="goodsDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="appendGoodsRows">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

interface UnitItem {
  unitId: string | number
  unitName: string
}

interface SaleReturnDetailRow {
  uid: string
  salesOrderDetailId?: string | number
  productId?: string | number
  productCode?: string
  productName?: string
  specificationModel?: string
  unitName?: string
  unitId?: string | number
  salesQuantity?: number
  deliveredQuantity?: number
  returnableQuantity?: number
  returnQuantity: number
  unitPrice: number
  amount: number
  remark?: string
}

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const detailTableRef = ref()
const detailRows = ref<SaleReturnDetailRow[]>([])
const selectedDetailRows = ref<SaleReturnDetailRow[]>([])
const saving = ref(false)
const generatingCode = ref(false)

const form = reactive({
  saleReturnsNo: '',
  saleReturnsDate: moment().format('YYYY-MM-DD'),
  salesOrderId: '',
  salesOrderNo: '',
  salesOrderDate: '',
  customerId: '',
  customerName: '',
  contactName: '',
  contactPhone: '',
  salesDepartment: '',
  salesOwner: '',
  saleReturnReason: '',
  remark: '',
})

const formRules = {
  saleReturnsNo: [{ required: true, message: '请生成退货单号', trigger: 'blur' }],
  saleReturnsDate: [{ required: true, message: '请选择退货日期', trigger: 'change' }],
  salesOrderNo: [{ required: true, message: '请选择销售单', trigger: 'change' }],
  customerName: [{ required: true, message: '请选择客户', trigger: 'change' }],
}

const summary = computed(() => {
  const totalQuantity = detailRows.value.reduce((sum, row) => sum + Number(row.returnQuantity || 0), 0)
  const totalAmount = detailRows.value.reduce((sum, row) => sum + Number(row.amount || 0), 0)
  return { totalQuantity, totalAmount }
})

const salesOrderDialog = reactive({
  visible: false,
  loading: false,
  list: [] as any[],
  search: {
    salesOrderNo: '',
    salesOrderStatus: '',
    customerName: '',
  },
})

const goodsDialog = reactive({
  visible: false,
  loading: false,
  list: [] as SaleReturnDetailRow[],
  selection: [] as SaleReturnDetailRow[],
})

const unitOptions = ref<UnitItem[]>([])

// 当前用户信息（用于审核人）
const currentUser = ref<string>('')

// 获取当前用户信息
const loadCurrentUser = async () => {
  try {
    const res = await myaxios.get('/api/User/GetMyProfile')
    const data = res?.data?.data || {}
    const name =
      data.userName ||
      data.realName ||
      data.nickname ||
      localStorage.getItem('username') ||
      ''
    if (name) {
      currentUser.value = name
      localStorage.setItem('username', name)
    } else {
      // 如果接口没有返回，尝试从缓存获取
      const cachedUser = localStorage.getItem('username') || ''
      currentUser.value = cachedUser
    }
  } catch (error) {
    console.warn('获取当前用户信息失败:', error)
    // 如果接口失败，尝试从缓存获取
    const cachedUser = localStorage.getItem('username') || ''
    currentUser.value = cachedUser
  }
}

// 加载单位列表
const loadUnitOptions = async () => {
  try {
    const res = await myaxios.get('/api/Unit/GetUnitList')
    if (res?.data?.code === 200) {
      unitOptions.value = (res.data.data || []).map((unit: any) => ({
        unitId: unit.unitId || unit.id,
        unitName: unit.unitName || unit.name || '',
      }))
    }
  } catch (error) {
    console.warn('加载单位列表失败:', error)
    unitOptions.value = []
  }
}

// 根据单位名称获取单位ID
const getUnitIdByName = (name?: string | number | null): number | null => {
  if (!name && name !== 0) return null
  const normalized = String(name)
  const hit = unitOptions.value.find(
    (unit) => unit.unitName === normalized || String(unit.unitId) === normalized,
  )
  if (hit) return Number(hit.unitId)
  return null
}

// 编号规则相关常量
const NUMBER_RULE_TARGET_CODE = 'SaleReturns'
const NUMBER_RULE_TARGET_NAME = '销售退货单号'
const TIME_SEGMENT_ORDER = ['YYYY', 'YY', 'MM', 'DD', 'HH', 'MI', 'SS']
const pad = (num: number, len = 2) => `${num}`.padStart(len, '0')

// 根据编号规则构建编号
const buildCodeFromRule = (rule: any) => {
  const now = new Date()
  
  // 解析时间规则，支持"时分"等中文描述
  let timeRuleStr = rule?.timeRule || ''
  
  // 如果时间规则包含中文"时分"，转换为对应的英文标识
  if (timeRuleStr.includes('时分') || timeRuleStr.includes('时') || timeRuleStr.includes('分')) {
    // 检查是否包含"时"和"分"
    const hasHour = timeRuleStr.includes('时') || timeRuleStr.includes('HH')
    const hasMinute = timeRuleStr.includes('分') || timeRuleStr.includes('MI') || timeRuleStr.includes('MM')
    
    // 构建时间规则字符串
    const parts: string[] = []
    if (hasHour) parts.push('HH')
    if (hasMinute) parts.push('MI')
    timeRuleStr = parts.join(',')
  }
  
  const segments = timeRuleStr
    .split(',')
    .map((item: string) => item.trim().toUpperCase())
    .filter(Boolean)
    .sort((a: string, b: string) => {
      const idxA = TIME_SEGMENT_ORDER.indexOf(a)
      const idxB = TIME_SEGMENT_ORDER.indexOf(b)
      if (idxA === -1 && idxB === -1) return 0
      if (idxA === -1) return 1
      if (idxB === -1) return -1
      return idxA - idxB
    })
  
  const timePart = segments
    .map((seg: string) => {
      switch (seg) {
        case 'YYYY':
          return String(now.getFullYear())
        case 'YY':
          return String(now.getFullYear()).slice(-2)
        case 'MM':
          return pad(now.getMonth() + 1)
        case 'DD':
          return pad(now.getDate())
        case 'HH':
          return pad(now.getHours())
        case 'MI':
          return pad(now.getMinutes())
        case 'SS':
          return pad(now.getSeconds())
        default:
          return ''
      }
    })
    .join('')
  
  // 序列号长度从规则中读取，默认为2（根据图片显示）
  const serialLength = Number(rule?.serialLength ?? rule?.serialNumberLength ?? 2)
  
  // 尝试从规则中获取当前序列号，如果没有则从1开始
  // 注意：这里应该从后端获取下一个序列号，但如果没有接口，则使用规则中的currentNumber或从1开始
  let currentSerial = 1
  if (rule?.currentNumber !== undefined && rule?.currentNumber !== null) {
    currentSerial = Number(rule.currentNumber) + 1
  } else if (rule?.serialNumber !== undefined && rule?.serialNumber !== null) {
    currentSerial = Number(rule.serialNumber) + 1
  }
  
  // 序列号补零到指定长度
  const serial = String(currentSerial).padStart(serialLength > 0 ? serialLength : 2, '0')
  
  // 前缀从规则中读取，优先使用codePrefix，如果没有则使用prefix，最后默认为XSTH
  const prefix = rule?.codePrefix || rule?.prefix || rule?.numberPrefix || 'XSTH'
  
  const generatedCode = `${prefix}${timePart}${serial}`
  console.log('构建编号详情:', {
    prefix,
    timePart,
    serial,
    timeRule: rule?.timeRule,
    serialLength,
    currentSerial,
    generatedCode
  })
  
  return generatedCode
}

// 查询编号规则
const fetchNumberRule = async () => {
  const tryFetch = async (params?: Record<string, any>) => {
    const res = await myaxios.get('/api/Number/QueryNumberingRules', {
      params,
    })
    if (res?.data?.code !== 200) return []
    return Array.isArray(res?.data?.data) ? res.data.data : []
  }

  let rule: any | null = null
  try {
    // 优先使用targetName查询
    const list = await tryFetch({
      targetName: NUMBER_RULE_TARGET_NAME,
    })
    rule = list.find((r: any) => r?.targetName === NUMBER_RULE_TARGET_NAME) || list[0]
  } catch (err) {
    console.warn('QueryNumberingRules 带过滤条件失败，尝试无条件加载', err)
  }

  if (!rule) {
    try {
      const list = await tryFetch({
        targetCode: NUMBER_RULE_TARGET_CODE,
      })
      rule = list.find((r: any) => r?.targetCode === NUMBER_RULE_TARGET_CODE) || list[0]
    } catch (err) {
      console.warn('QueryNumberingRules 带targetCode失败，尝试无条件加载', err)
    }
  }

  if (!rule) {
    const list = await tryFetch()
    rule = list.find((r: any) => 
      r?.targetName === NUMBER_RULE_TARGET_NAME || 
      r?.targetCode === NUMBER_RULE_TARGET_CODE ||
      r?.targetName?.includes('销售退货')
    ) || list[0]
  }

  if (!rule) {
    throw new Error('未配置销售退货单号编号规则，请先在"编号规则"中添加')
  }
  return rule
}

// 生成编号（优先使用GenerateNumber接口，失败则使用规则生成）
const handleGenerateNo = async () => {
  if (generatingCode.value) return
  generatingCode.value = true
  try {
    // 优先使用 GenerateNumber 接口，确保传递正确的参数
    const res = await myaxios.get('/api/Number/GenerateNumber', {
      params: { 
        targetCode: NUMBER_RULE_TARGET_CODE,
        targetName: NUMBER_RULE_TARGET_NAME,
      },
    })
    if (res?.data?.code === 200 && res.data?.data) {
      const generatedNo = String(res.data.data)
      // 验证生成的编号格式是否符合规则（应该包含XSTH前缀，而不是NO）
      // 如果格式不对（比如以NO开头），则使用规则生成
      if (generatedNo && generatedNo.startsWith('XSTH')) {
        form.saleReturnsNo = generatedNo
        ElMessage.success('销售退货单号生成成功')
        return
      } else {
        console.warn('GenerateNumber 返回的编号格式不符合规则，使用规则生成:', generatedNo)
        throw new Error('编号格式不符合规则')
      }
    }
    throw new Error(res?.data?.message || '编号服务返回格式不正确')
  } catch (error) {
    console.warn('GenerateNumber 接口不可用或返回格式不正确，使用编号规则生成', error)
    try {
      // 查询编号规则并生成
      const rule = await fetchNumberRule()
      console.log('获取到的编号规则:', {
        targetName: rule?.targetName,
        codePrefix: rule?.codePrefix,
        prefix: rule?.prefix,
        timeRule: rule?.timeRule,
        serialLength: rule?.serialLength,
        currentNumber: rule?.currentNumber,
      })
      
      // 根据规则生成编号
      const generatedNo = buildCodeFromRule(rule)
      console.log('根据规则生成的编号:', generatedNo)
      
      if (generatedNo && generatedNo.length > 0 && generatedNo.startsWith('XSTH')) {
        form.saleReturnsNo = generatedNo
        ElMessage.success('销售退货单号生成成功')
      } else {
        throw new Error(`根据规则生成的编号格式不正确: ${generatedNo}`)
      }
    } catch (ruleError: any) {
      console.error('生成编号失败:', ruleError)
      // 最后的备选方案：使用临时编号（但应该尽量避免）
      const now = new Date()
      const hh = pad(now.getHours())
      const mi = pad(now.getMinutes())
      form.saleReturnsNo = `XSTH${hh}${mi}00`
      ElMessage.warning(ruleError?.message || '自动生成失败，已使用临时编号，请检查编号规则配置')
    }
  } finally {
    generatingCode.value = false
  }
}

const openSalesOrderDialog = () => {
  salesOrderDialog.visible = true
  // 打开对话框时，如果没有选择状态，默认只显示未出库和部分出库
  if (!salesOrderDialog.search.salesOrderStatus) {
    salesOrderDialog.search.salesOrderStatus = ''
  }
  // 每次打开都重新加载，确保数据是最新的
  loadSalesOrders()
}

const resetSalesOrderDialog = () => {
  salesOrderDialog.search.salesOrderNo = ''
  salesOrderDialog.search.salesOrderStatus = ''
  salesOrderDialog.search.customerName = ''
  loadSalesOrders()
}

// 销售订单状态选项
const SALES_ORDER_STATUS_OPTIONS = [
  { value: 0, label: '草稿', tagType: 'info' },
  { value: 1, label: '待审核', tagType: 'warning' },
  { value: 2, label: '驳回', tagType: 'danger' },
  { value: 3, label: '未出库', tagType: 'info' },
  { value: 4, label: '部分出库', tagType: 'warning' },
  { value: 5, label: '已出库', tagType: 'success' },
  { value: 6, label: '已完成', tagType: 'success' },
  { value: 7, label: '已关闭', tagType: 'danger' },
]

// 获取销售订单状态文本
const getSalesOrderStatusText = (status: number | string | undefined): string => {
  if (status === undefined || status === null) return '未知'
  const statusNum = Number(status)
  const option = SALES_ORDER_STATUS_OPTIONS.find((opt) => opt.value === statusNum)
  return option?.label || '未知'
}

// 获取销售订单状态标签类型
const getSalesOrderStatusTag = (status: number | string | undefined): string => {
  if (status === undefined || status === null) return 'info'
  const statusNum = Number(status)
  const option = SALES_ORDER_STATUS_OPTIONS.find((opt) => opt.value === statusNum)
  return option?.tagType || 'info'
}

// 映射销售订单数据，确保字段正确
const mapSalesOrderItem = (item: any) => {
  return {
    ...item,
    // 销售单号
    salesOrderNo: item.salesOrderNo || item.salesOrderNO || item.orderNo || '',
    // 销售单ID
    salesOrderId: item.salesOrderId || item.id || item.salesOrderID || '',
    // 单据状态
    salesOrderStatus: item.salesOrderStatus ?? item.status ?? item.orderStatus ?? 0,
    // 销售日期
    salesOrderDate: item.salesOrderDate || item.orderDate || item.createTime || '',
    // 客户信息
    customerId: item.customerId || item.customerID || '',
    customerName: item.customerName || item.customer || '',
    // 销售部门 - 尝试多个可能的字段名
    organizationName: item.organizationName || item.salesDepartment || item.salesOrderDepartment || item.departmentName || '',
    salesDepartment: item.organizationName || item.salesDepartment || item.salesOrderDepartment || item.departmentName || '',
    // 销售负责人 - 尝试多个可能的字段名
    userName: item.userName || item.salesOwner || item.salesOrderUser || item.salesUser || item.ownerName || '',
    salesOwner: item.userName || item.salesOwner || item.salesOrderUser || item.salesUser || item.ownerName || '',
    // 金额 - 尝试多个可能的字段名
    salesOrderAmount: Number(item.salesOrderAmount ?? item.saleAmount ?? item.amount ?? item.totalAmount ?? item.orderAmount ?? 0),
    saleAmount: Number(item.salesOrderAmount ?? item.saleAmount ?? item.amount ?? item.totalAmount ?? item.orderAmount ?? 0),
    // 联系人信息
    salesContact: item.salesContact || item.contactName || item.contact || '',
    salesContactPhone: item.salesContactPhone || item.contactPhone || item.contactMethod || '',
  }
}

const loadSalesOrders = async () => {
  salesOrderDialog.loading = true
  try {
    // 如果用户选择了特定状态，只查询该状态
    if (salesOrderDialog.search.salesOrderStatus !== '' && salesOrderDialog.search.salesOrderStatus !== null && salesOrderDialog.search.salesOrderStatus !== undefined) {
      const params: Record<string, any> = {
        salesOrderNo: salesOrderDialog.search.salesOrderNo,
        customerName: salesOrderDialog.search.customerName,
        salesOrderStatus: salesOrderDialog.search.salesOrderStatus,
        pageindex: 1,
        pagesize: 100,
      }
      
      const res = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params })
      if (res?.data?.code === 200 || res?.data?.success) {
        const section = res.data?.data ?? res.data
        const rawList = normalizeList(section)
        salesOrderDialog.list = rawList.map(mapSalesOrderItem)
      } else {
        salesOrderDialog.list = []
        ElMessage.error(res?.data?.message || '获取销售单列表失败')
      }
    } else {
      // 默认情况：分别查询未出库（3）和部分出库（4）状态，然后合并结果
      const allResults: any[] = []
      
      // 查询未出库状态（3）
      try {
        const params3: Record<string, any> = {
          salesOrderNo: salesOrderDialog.search.salesOrderNo,
          customerName: salesOrderDialog.search.customerName,
          salesOrderStatus: 3,
          pageindex: 1,
          pagesize: 100,
        }
        const res3 = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params: params3 })
        if (res3?.data?.code === 200 || res3?.data?.success) {
          const section3 = res3.data?.data ?? res3.data
          const rawList3 = normalizeList(section3)
          allResults.push(...rawList3)
        }
      } catch (error3) {
        console.warn('查询未出库状态失败:', error3)
      }
      
      // 查询部分出库状态（4）
      try {
        const params4: Record<string, any> = {
          salesOrderNo: salesOrderDialog.search.salesOrderNo,
          customerName: salesOrderDialog.search.customerName,
          salesOrderStatus: 4,
          pageindex: 1,
          pagesize: 100,
        }
        const res4 = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params: params4 })
        if (res4?.data?.code === 200 || res4?.data?.success) {
          const section4 = res4.data?.data ?? res4.data
          const rawList4 = normalizeList(section4)
          allResults.push(...rawList4)
        }
      } catch (error4) {
        console.warn('查询部分出库状态失败:', error4)
      }
      
      // 映射数据并去重（根据销售单号）
      const mappedList = allResults.map(mapSalesOrderItem)
      const uniqueMap = new Map()
      mappedList.forEach((item) => {
        const key = item.salesOrderId || item.salesOrderNo
        if (key && !uniqueMap.has(key)) {
          uniqueMap.set(key, item)
        }
      })
      salesOrderDialog.list = Array.from(uniqueMap.values())
      
      // 如果合并后没有数据，尝试不传状态参数，然后在前端过滤
      if (salesOrderDialog.list.length === 0) {
        const params: Record<string, any> = {
          salesOrderNo: salesOrderDialog.search.salesOrderNo,
          customerName: salesOrderDialog.search.customerName,
          pageindex: 1,
          pagesize: 200,
        }
        const res = await myaxios.get('/api/SalesOrder/GetSalesOrders', { params })
        if (res?.data?.code === 200 || res?.data?.success) {
          const section = res.data?.data ?? res.data
          const rawList = normalizeList(section)
          const mappedList = rawList.map(mapSalesOrderItem)
          // 前端过滤：只显示未出库（3）和部分出库（4）
          salesOrderDialog.list = mappedList.filter((item: any) => {
            const status = Number(item.salesOrderStatus ?? item.status ?? -1)
            return status === 3 || status === 4 // 未出库或部分出库
          })
        }
      }
    }
    
    // 调试日志：检查是否有金额为0的项
    const zeroAmountItems = salesOrderDialog.list.filter((item) => (item.salesOrderAmount || 0) === 0)
    if (zeroAmountItems.length > 0) {
      console.warn(`有 ${zeroAmountItems.length} 个销售单的金额为0，请检查数据`, zeroAmountItems)
    }
  } catch (error) {
    console.error('获取销售单失败', error)
    salesOrderDialog.list = []
    ElMessage.error('获取销售单列表失败')
  } finally {
    salesOrderDialog.loading = false
  }
}

const handlePickSalesOrder = async (row: any) => {
  salesOrderDialog.visible = false
  if (!row) return
  
  // 使用映射后的数据，确保字段正确
  const mappedRow = mapSalesOrderItem(row)
  
  // 同步销售单基本信息到表单
  form.salesOrderId = String(mappedRow.salesOrderId || mappedRow.id || '')
  form.salesOrderNo = String(mappedRow.salesOrderNo || mappedRow.saleOrderNo || mappedRow.orderNo || '')
  form.salesOrderDate = mappedRow.salesOrderDate || mappedRow.orderDate || ''
  
  // 同步客户信息到表单
  form.customerId = String(mappedRow.customerId || mappedRow.customerID || '')
  form.customerName = String(mappedRow.customerName || mappedRow.customer || '')
  
  // 同步联系人信息
  form.contactName = String(mappedRow.salesContact || mappedRow.contactName || mappedRow.linkMan || mappedRow.contact || '')
  form.contactPhone = String(mappedRow.salesContactPhone || mappedRow.contactPhone || mappedRow.linkPhone || mappedRow.contactMethod || '')
  
  // 同步部门信息
  form.salesDepartment = String(mappedRow.organizationName || mappedRow.salesDepartment || mappedRow.salesOrderDepartment || mappedRow.departmentName || '')
  
  // 同步负责人信息
  form.salesOwner = String(mappedRow.userName || mappedRow.salesOwner || mappedRow.salesOrderUser || mappedRow.salesUser || mappedRow.ownerName || '')
  
  console.log('选择销售单后同步的数据:', {
    salesOrderNo: form.salesOrderNo,
    customerName: form.customerName,
    salesOrderId: form.salesOrderId,
    mappedRow,
  })
  
  // 清空现有明细
  detailRows.value = []
  await loadSalesOrderGoods(form.salesOrderId)
}

// 销售订单明细中可能包含单价的字段名列表（按优先级排序）
const SALES_ORDER_PRICE_FIELDS = [
  'unitPrice',
  'salesPrice',
  'salePrice',
  'salesUnitPrice',
  'productSalePrice',
  'productSaleMoney',
  'productOutMoney',
  'productoutmoney',
  'outPrice',
  'price',
  'productPrice',
  'amount',
  'salesAmount',
]

// 从销售订单明细项中解析单价
const resolveSalesOrderDetailPrice = (item: any): number => {
  // 优先尝试直接字段
  for (const key of SALES_ORDER_PRICE_FIELDS) {
    const value = item?.[key]
    if (value !== undefined && value !== null && value !== '') {
      const num = Number(value)
      if (!Number.isNaN(num) && Number.isFinite(num) && num > 0) {
        return num
      }
    }
  }
  
  // 如果单价字段不存在或为0，尝试从金额和数量计算
  const quantity = Number(item?.quantity ?? item?.salesQuantity ?? 0)
  const amount = Number(item?.amount ?? item?.salesAmount ?? 0)
  if (quantity > 0 && amount > 0) {
    const calculatedPrice = Number((amount / quantity).toFixed(4))
    if (calculatedPrice > 0) {
      return calculatedPrice
    }
  }
  
  // 如果都找不到，返回0（但会在控制台警告）
  console.warn('无法从销售订单明细中获取单价，item:', item)
  return 0
}

const loadSalesOrderGoods = async (salesOrderId: string | number) => {
  if (!salesOrderId) return
  goodsDialog.loading = true
  try {
    const res = await myaxios.get('/api/SalesOrder/GetSalesOrderDetails', {
      params: { salesOrderId },
    })
    if (res?.data?.code === 200 || res?.data?.success) {
      const section = res.data?.data ?? res.data
      goodsDialog.list = normalizeList(section).map((item: any, index: number) => {
        const resolvedPrice = resolveSalesOrderDetailPrice(item)
        if (resolvedPrice === 0) {
          console.warn(`销售订单明细项 ${item.productName || item.productCode || index} 的单价为0，请检查数据`, item)
        }
        return {
          uid: `${item.salesOrderDetailId || item.id || index}`,
          salesOrderDetailId: item.salesOrderDetailId || item.id,
          productId: item.productId,
          productName: item.productName,
          productCode: item.productCode,
          specificationModel: item.specificationModel || item.specification,
          unitName: item.unitName || item.unit,
          salesQuantity: Number(item.quantity || item.salesQuantity || 0),
          deliveredQuantity: Number(item.deliveredQuantity || item.outboundQuantity || 0),
          returnableQuantity:
            Number(item.returnableQuantity ?? item.quantity ?? 0) -
            Number(item.returnedQuantity ?? 0),
          unitPrice: resolvedPrice,
          returnQuantity: 0,
          amount: 0,
        }
      })
      
      // 检查是否有单价为0的项
      const zeroPriceItems = goodsDialog.list.filter((item) => item.unitPrice === 0)
      if (zeroPriceItems.length > 0) {
        console.warn(`有 ${zeroPriceItems.length} 个货品的单价为0，请检查销售订单明细数据`)
      }
    } else {
      goodsDialog.list = []
      ElMessage.error(res?.data?.message || '获取销售明细失败')
    }
  } catch (error) {
    console.error('获取销售明细失败', error)
    goodsDialog.list = []
    ElMessage.error('获取销售明细失败')
  } finally {
    goodsDialog.loading = false
  }
}

const openGoodsDialog = () => {
  if (!form.salesOrderId) {
    ElMessage.warning('请先选择销售单')
    return
  }
  goodsDialog.visible = true
  if (!goodsDialog.list.length) {
    loadSalesOrderGoods(form.salesOrderId)
  }
}

const goodsDialogSelectionChange = (rows: SaleReturnDetailRow[]) => {
  goodsDialog.selection = rows
}

const appendGoodsRows = () => {
  if (!goodsDialog.selection.length) {
    ElMessage.warning('请选择需要添加的货品')
    return
  }
  
  const zeroPriceItems: string[] = []
  
  goodsDialog.selection.forEach((item) => {
    // 检查单价是否为0
    if (!item.unitPrice || item.unitPrice === 0) {
      zeroPriceItems.push(item.productName || item.productCode || '未知货品')
    }
    
    const exists = detailRows.value.find(
      (row) => row.salesOrderDetailId === item.salesOrderDetailId || row.productId === item.productId,
    )
    if (exists) {
      // 更新已存在的项，确保单价正确
      exists.returnableQuantity = item.returnableQuantity
      if (item.unitPrice && item.unitPrice > 0) {
        exists.unitPrice = item.unitPrice
        recalcRow(exists)
      }
    } else {
      // 确保单价大于0
      const finalUnitPrice = item.unitPrice && item.unitPrice > 0 ? item.unitPrice : 0
      const returnQty = item.returnableQuantity ?? item.salesQuantity ?? 0
      
      detailRows.value.push({
        uid: `${item.salesOrderDetailId || item.productId || Date.now()}`,
        salesOrderDetailId: item.salesOrderDetailId,
        productId: item.productId,
        productName: item.productName,
        productCode: item.productCode,
        specificationModel: item.specificationModel,
        unitName: item.unitName,
        salesQuantity: item.salesQuantity,
        deliveredQuantity: item.deliveredQuantity,
        returnableQuantity: item.returnableQuantity ?? item.salesQuantity,
        returnQuantity: returnQty,
        unitPrice: finalUnitPrice,
        amount: Number((finalUnitPrice * returnQty).toFixed(2)),
        remark: '',
      })
    }
  })
  
  // 如果有单价为0的项，提示用户
  if (zeroPriceItems.length > 0) {
    ElMessage.warning(`以下货品的单价为0，请检查销售订单明细：${zeroPriceItems.join('、')}`)
  }
  
  goodsDialog.visible = false
}

const handleDetailSelectionChange = (rows: SaleReturnDetailRow[]) => {
  selectedDetailRows.value = rows
}

const removeDetailRow = (row: SaleReturnDetailRow) => {
  detailRows.value = detailRows.value.filter((item) => item.uid !== row.uid)
}

const handleRemoveSelected = () => {
  detailRows.value = detailRows.value.filter(
    (item) => !selectedDetailRows.value.some((selected) => selected.uid === item.uid),
  )
  selectedDetailRows.value = []
}

const recalcRow = (row: SaleReturnDetailRow) => {
  const quantity = Number(row.returnQuantity || 0)
  const price = Number(row.unitPrice || 0)
  row.amount = Number((quantity * price).toFixed(2))
}

const validateDetails = () => {
  if (!detailRows.value || detailRows.value.length === 0) {
    ElMessage.warning('退货明细不能为空，请添加退货明细')
    return false
  }
  
  // 过滤掉无效的行（没有 productId 或数量/单价无效）
  const validRows = detailRows.value.filter((row) => {
    const hasProductId = !!row.productId
    const returnQty = Number(row.returnQuantity || 0)
    const unitPrice = Number(row.unitPrice || 0)
    return hasProductId && returnQty > 0 && unitPrice > 0
  })
  
  if (validRows.length === 0) {
    // 详细检查每个字段，给出更具体的错误提示
    const invalidRows = detailRows.value.map((row, index) => {
      const issues: string[] = []
      if (!row.productId) issues.push('缺少货品ID')
      if (Number(row.returnQuantity || 0) <= 0) issues.push('退货数量必须大于0')
      if (Number(row.unitPrice || 0) <= 0) issues.push('退货单价必须大于0')
      return issues.length > 0 ? { index: index + 1, productName: row.productName || '未知', issues } : null
    }).filter(Boolean)
    
    console.error('验证失败，无效的明细行:', invalidRows)
    ElMessage.warning('退货明细不能为空，请填写完整的退货数量和单价（必须大于0）')
    return false
  }
  
  // 检查是否有无效的行（用于提示用户）
  const invalid = detailRows.value.find(
    (row) => {
      const hasProductId = !!row.productId
      const returnQty = Number(row.returnQuantity || 0)
      const unitPrice = Number(row.unitPrice || 0)
      return !hasProductId || returnQty <= 0 || unitPrice <= 0
    }
  )
  if (invalid) {
    console.warn('发现无效的明细行:', invalid)
    ElMessage.warning('请填写完整的退货数量和单价（必须大于0）')
    return false
  }
  
  return true
}

const buildPayload = () => {
  // 过滤并构建有效的明细数据（要求单价 > 0）
  const details = detailRows.value
    .filter((row) => {
      const hasProductId = !!row.productId
      const returnQty = Number(row.returnQuantity || 0)
      const unitPrice = Number(row.unitPrice || 0)
      return hasProductId && returnQty > 0 && unitPrice > 0
    })
    .map((row) => {
      const returnQty = Number(row.returnQuantity || 0)
      const unitPrice = Number(row.unitPrice || 0)
      const amount = Number(row.amount || 0) || Number((returnQty * unitPrice).toFixed(2))
      
      // 获取单位ID（后端期望 unitName 是单位ID，整数类型）
      const unitNameValue = row.unitName || ''
      let unitIdValue = getUnitIdByName(unitNameValue || row.unitId || null)
      
      // 如果找不到单位ID，尝试使用 row.unitId，如果还是没有，使用默认值或警告
      if (unitIdValue === null) {
        if (row.unitId) {
          unitIdValue = Number(row.unitId)
        } else {
          console.warn(`无法找到单位ID，单位名称: ${unitNameValue}，货品: ${row.productName}`)
          // 如果实在找不到，设置为 0 或 null（根据后端要求）
          unitIdValue = 0
        }
      }
      
      // 确保所有字段都有值，特别是数字类型
      return {
        salesOrderDetailId: row.salesOrderDetailId || null,
        productId: Number(row.productId) || 0,
        productCode: row.productCode || '',
        productName: row.productName || '',
        specificationModel: row.specificationModel || '',
        unitName: unitIdValue, // 后端期望是单位ID（整数），不是单位名称
        unitDisplayName: String(unitNameValue), // 单位名称（用于显示）
        unitId: unitIdValue, // 兼容字段
        quantity: returnQty,
        returnQuantity: returnQty, // 兼容字段
        unitPrice: unitPrice,
        returnUnitPrice: unitPrice, // 兼容字段
        amount: amount,
        returnAmount: amount, // 兼容字段
        remark: row.remark || '',
      }
    })
  
  // 确保明细不为空
  if (!details || details.length === 0) {
    console.error('构建payload时明细为空，原始数据:', detailRows.value)
    throw new Error('退货明细不能为空')
  }
  
  console.log('构建的明细数据:', details)
  
  // 构建主表数据，确保所有必填字段都有值
  const payload: any = {
    saleReturnsNo: form.saleReturnsNo || '',
    saleReturnsDate: form.saleReturnsDate || moment().format('YYYY-MM-DD'),
    salesOrderId: form.salesOrderId || '',
    salesOrderNo: form.salesOrderNo || '',
    customerId: form.customerId || '',
    customerName: form.customerName || '',
    contactName: form.contactName || '',
    contactPhone: form.contactPhone || '',
    salesDepartment: form.salesDepartment || '',
    salesOwner: form.salesOwner || '',
    saleReturnReason: form.saleReturnReason || '',
    remark: form.remark || '',
    saleReturnsQuantity: Number(summary.value.totalQuantity) || 0,
    saleReturnsAmount: Number(summary.value.totalAmount) || 0,
    // 审核人和审核时间：提交时自动设置为当前用户和当前时间
    auditor: currentUser.value,
    auditTime: moment().format('YYYY-MM-DD HH:mm:ss'),
  }
  
  // 添加明细数据，尝试多个可能的字段名
  payload.saleReturnsDetails = details
  payload.goodsDetails = details
  payload.details = details
  payload.saleReturnDetails = details
  
  return payload
}

const handleSave = async () => {
  if (!formRef.value) return
  
  // 点击保存时自动生成退货单号（在表单验证之前）
  if (!form.saleReturnsNo || form.saleReturnsNo.trim() === '') {
    try {
      await handleGenerateNo()
      if (!form.saleReturnsNo || form.saleReturnsNo.trim() === '') {
        ElMessage.warning('退货单号生成失败，请手动生成')
        return
      }
    } catch (error) {
      console.error('生成退货单号失败:', error)
      ElMessage.warning('退货单号生成失败，请手动生成')
      return
    }
  }
  
  // 生成单号后再验证表单
  await formRef.value.validate()
  
  // 验证明细
  if (!validateDetails()) {
    return
  }
  
  saving.value = true
  try {
    const payload = buildPayload()
    console.log('保存销售退货，payload:', JSON.stringify(payload, null, 2))
    console.log('明细数据详情:', payload.saleReturnsDetails)
    
    const res = await myaxios.post('/api/SaleReturns/CreateSaleReturns', payload)
    if (res?.data?.code === 200) {
      ElMessage.success(res?.data?.message || '保存成功')
      router.push('/getsalereturn')
    } else {
      const errorMsg = res?.data?.message || '保存失败'
      console.error('保存失败，后端返回:', res?.data)
      // 处理后端返回的明细相关错误
      if (errorMsg.includes('明细') || errorMsg.includes('不能为空')) {
        ElMessage.error(`保存失败：${errorMsg}。请确保所有退货明细的退货数量和退货单价都已填写且大于0`)
      } else {
        ElMessage.error(errorMsg)
      }
    }
  } catch (error: any) {
    console.error('保存销售退货失败:', error)
    console.error('错误详情:', error?.response?.data)
    
    // 解析后端返回的详细错误信息
    const errorData = error?.response?.data
    let errorMsg = errorData?.message || errorData?.title || error?.message || '保存失败，请稍后重试'
    
    // 处理验证错误（400错误通常包含详细的验证信息）
    if (errorData?.errors && typeof errorData.errors === 'object') {
      const validationErrors: string[] = []
      Object.keys(errorData.errors).forEach((key) => {
        const fieldErrors = errorData.errors[key]
        if (Array.isArray(fieldErrors)) {
          fieldErrors.forEach((err: string) => {
            validationErrors.push(`${key}: ${err}`)
          })
        } else if (typeof fieldErrors === 'string') {
          validationErrors.push(`${key}: ${fieldErrors}`)
        }
      })
      
      if (validationErrors.length > 0) {
        errorMsg = `验证失败：${validationErrors.join('；')}`
        console.error('验证错误详情:', validationErrors)
      }
    }
    
    // 处理后端返回的明细相关错误
    if (errorMsg.includes('明细') || errorMsg.includes('不能为空') || errorMsg.includes('Details')) {
      ElMessage.error(`${errorMsg}。请确保所有退货明细的退货数量和退货单价都已填写且大于0`)
    } else {
      ElMessage.error(errorMsg)
    }
  } finally {
    saving.value = false
  }
}

const handleBack = () => {
  router.push('/getsalereturn')
}

const handleReset = () => {
  formRef.value?.resetFields()
  form.saleReturnsNo = ''
  form.saleReturnsDate = moment().format('YYYY-MM-DD')
  form.salesOrderId = ''
  form.salesOrderNo = ''
  form.salesOrderDate = ''
  form.customerId = ''
  form.customerName = ''
  form.contactName = ''
  form.contactPhone = ''
  form.salesDepartment = ''
  form.salesOwner = ''
  form.saleReturnReason = ''
  form.remark = ''
  detailRows.value = []
  selectedDetailRows.value = []
}

const handleSaveAndNew = async () => {
  if (!formRef.value) return
  
  // 点击保存并新增时自动生成退货单号（在表单验证之前）
  if (!form.saleReturnsNo || form.saleReturnsNo.trim() === '') {
    try {
      await handleGenerateNo()
      if (!form.saleReturnsNo || form.saleReturnsNo.trim() === '') {
        ElMessage.warning('退货单号生成失败，请手动生成')
        return
      }
    } catch (error) {
      console.error('生成退货单号失败:', error)
      ElMessage.warning('退货单号生成失败，请手动生成')
      return
    }
  }
  
  // 生成单号后再验证表单
  await formRef.value.validate()
  
  // 验证明细
  if (!validateDetails()) {
    return
  }
  
  saving.value = true
  try {
    const payload = buildPayload()
    console.log('保存并新增销售退货，payload:', JSON.stringify(payload, null, 2))
    console.log('明细数据详情:', payload.saleReturnsDetails)
    
    const res = await myaxios.post('/api/SaleReturns/CreateSaleReturns', payload)
    if (res?.data?.code === 200) {
      ElMessage.success(res?.data?.message || '保存成功')
      handleReset()
      await handleGenerateNo()
    } else {
      const errorMsg = res?.data?.message || '保存失败'
      console.error('保存失败，后端返回:', res?.data)
      // 处理后端返回的明细相关错误
      if (errorMsg.includes('明细') || errorMsg.includes('不能为空')) {
        ElMessage.error(`保存失败：${errorMsg}。请确保所有退货明细的退货数量和退货单价都已填写且大于0`)
      } else {
        ElMessage.error(errorMsg)
      }
    }
  } catch (error: any) {
    console.error('保存销售退货失败:', error)
    console.error('错误详情:', error?.response?.data)
    
    // 解析后端返回的详细错误信息
    const errorData = error?.response?.data
    let errorMsg = errorData?.message || errorData?.title || error?.message || '保存失败，请稍后重试'
    
    // 处理验证错误（400错误通常包含详细的验证信息）
    if (errorData?.errors && typeof errorData.errors === 'object') {
      const validationErrors: string[] = []
      Object.keys(errorData.errors).forEach((key) => {
        const fieldErrors = errorData.errors[key]
        if (Array.isArray(fieldErrors)) {
          fieldErrors.forEach((err: string) => {
            validationErrors.push(`${key}: ${err}`)
          })
        } else if (typeof fieldErrors === 'string') {
          validationErrors.push(`${key}: ${fieldErrors}`)
        }
      })
      
      if (validationErrors.length > 0) {
        errorMsg = `验证失败：${validationErrors.join('；')}`
        console.error('验证错误详情:', validationErrors)
      }
    }
    
    // 处理后端返回的明细相关错误
    if (errorMsg.includes('明细') || errorMsg.includes('不能为空') || errorMsg.includes('Details')) {
      ElMessage.error(`${errorMsg}。请确保所有退货明细的退货数量和退货单价都已填写且大于0`)
    } else {
      ElMessage.error(errorMsg)
    }
  } finally {
    saving.value = false
  }
}

const normalizeList = (payload: any) => {
  if (!payload) return []
  if (Array.isArray(payload)) return payload
  if (Array.isArray(payload?.data)) return payload.data
  if (Array.isArray(payload?.records)) return payload.records
  if (Array.isArray(payload?.list)) return payload.list
  if (Array.isArray(payload?.items)) return payload.items
  return []
}

const formatDate = (value?: string) => {
  if (!value) return '-'
  return moment(value).format('YYYY-MM-DD')
}

// 页面加载时初始化
onMounted(() => {
  loadUnitOptions()
  loadCurrentUser()
})
</script>

<style scoped>
.sale-return-create-page {
  padding: 16px 16px 96px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 16px;
}

.form-card,
.detail-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-header .actions {
  display: flex;
  gap: 8px;
}

.info-form {
  margin-top: 8px;
}

.detail-summary {
  margin-top: 12px;
  padding: 12px 16px;
  background: #f9fafc;
  border: 1px dashed #e4e7ed;
  border-radius: 4px;
  display: flex;
  gap: 24px;
  color: #606266;
  font-size: 14px;
}

.detail-summary strong {
  color: #303133;
  font-weight: 600;
}

.fixed-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  padding: 12px 24px;
  display: flex;
  justify-content: flex-end;
  z-index: 20;
}

.footer-actions {
  display: flex;
  gap: 12px;
}

.dialog-form {
  margin-bottom: 12px;
}

.dialog-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.amount-text {
  font-weight: 500;
  color: #303133;
}

.required-label {
  color: #f56c6c;
}

.required-label::before {
  content: '* ';
  color: #f56c6c;
}
</style>

